﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenPhotoAlbum.DbAccess;

namespace OpenPhotoAlbum.BusinessLogics
{
    public class ServiceManager
    {
        #region Singleton

        private static readonly ServiceManager _instance = new ServiceManager();

        static ServiceManager() { }

        private ServiceManager() { }

        public static ServiceManager Instance { get { return _instance; } }

        #endregion

		private static readonly Guid CacheKeyBlockedIPs = Guid.NewGuid();

		private HashSet<string> BlockedIPs
		{
			get
			{
				if (CacheManager.Instance.ContainsKey(CacheKeyBlockedIPs))
					return CacheManager.Instance.ReadCache<HashSet<string>>(CacheKeyBlockedIPs);

				HashSet<string> blockedIPs = new HashSet<string>();
				DataClassesUADataContext context = new DataClassesUADataContext();
				IEnumerable<DbAccess.IpAddress> arr = context.IpAddresses;
				foreach (DbAccess.IpAddress item in arr)
				{
					if (!string.IsNullOrEmpty(item.Address)) { blockedIPs.Add(item.Address); }
				}
				CacheManager.Instance.WriteCache<HashSet<string>>(CacheKeyBlockedIPs, blockedIPs);
				return blockedIPs;
			}
		}

        public bool IsApproved()
        {
            return IsApproved(HttpContext.Current.Request.UserHostAddress);
        }

        public bool IsApproved(string ip)
        {
			return !BlockedIPs.Contains(ip);
        }

        public void AddIpAddress(string ip)
        {
            if (string.IsNullOrEmpty(ip)) { return; }

            DataClassesUADataContext context = new DataClassesUADataContext();
            context.IpAddresses.InsertOnSubmit(
				new IpAddress() { Address = ip, StartingDate = DateTime.UtcNow });
            context.SubmitChanges();
        }

        public void DeleteIpAddress(string ip)
        {
            if (string.IsNullOrEmpty(ip)) { return; }

            DataClassesUADataContext context = new DataClassesUADataContext();
            var results = from address in context.IpAddresses
                          where address.Equals(ip)
                          select address;
            context.IpAddresses.DeleteAllOnSubmit(results);
            context.SubmitChanges();
        }
    }
}
